package com.xilihui.xlh.business.activitys;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xilihui.xlh.R;
import com.xilihui.xlh.alipay.AuthResult;
import com.xilihui.xlh.alipay.PayResult;
import com.xilihui.xlh.alipay.util.OrderInfoUtil2_0;
import com.xilihui.xlh.business.activitys.store.ConfirmOrderActivity;
import com.xilihui.xlh.business.dialogs.PatternDialog;
import com.xilihui.xlh.business.entities.AddOrderEntity;
import com.xilihui.xlh.business.entities.BalanceEntity;
import com.xilihui.xlh.business.requests.MyAppointmentRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static anet.channel.util.Utils.context;

/**
 * Created by Administrator on 2018/5/31.
 */

public class ConfirmListingActivity extends BaseCompatActivity{
    
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerView;
    @BindView(R.id.tv_totalPrice)
    TextView tv_totalPrice;
    
    BaseAdapter<BalanceEntity.SelectedGoodsBean> beanBaseAdapter;
    BalanceEntity balanceEntity;
    ArrayList<BalanceEntity.SelectedGoodsBean> data = new ArrayList<>();
    
    String wa_id = "";
    String agent_id = "";
    int type = 0;
    String goods_id = "";
    String item_id = "";
    int num = 0;

    DecimalFormat decimalFormat=new DecimalFormat("0.00");
    
    View viewHead;
    
    AddOrderEntity.PaymentParamsBean.WeixinBean weixinBean;

    /** 支付宝支付业务：入参app_id */
//    public static final String APPID = "2016091300501833";
    public static String orderInfo = "";
    

//    /** 支付宝账户登录授权业务：入参pid值 */
//    public static final String PID = "";
//    /** 支付宝账户登录授权业务：入参target_id值 */
//    public static final String TARGET_ID = "";
//
//    /** 商户私钥，pkcs8格式 */
//    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
//    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
//    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
//    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
//    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
//    public static final String RSA2_PRIVATE = "MIIEpAIBAAKCAQEA1eBWE1sxo1PuyNQWopGrVa59Mhf6NkbUpCzaJUgI+mNNtRKhNbtOCE7yp5PqKeJUrNLkwkeJ3UhCZ1Ly9TFbjbXn0TR/69ebuZ+T+eHOg7xN2j8MNRU6HepLHhCKVy0ZnbzqudJ6OQMRIzUU2mv9mHnbFr4FMfLCQJMgdt3hfEPxKEhpx7lrcqfatsX8UJUoYVNtdCzU9J1M5PubKbuXSXQ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yjZN03N61SkHrOEdIzs48eHxZJGzAGXduw1VgWZHvpyqhboYV1CuygNdQnD9YdLIuajFkyKZz6Lj/wM95dOxOdmECgYBPHlHmGRZ7OIZ5EM+cfdlc8Dt9nl485HAEjGP1JMr/sqKcBQZk4Dz26ByaIRK8BvDAYRN/5jf8AqKsHV5uEjnLTEsL0/LLpiti+qOaYQDnE1cdM5ONzOcNSmhjr+i3oMuNYEIF4oHa7R5Aj88zOlWvI9EZrAFiTV3UqopXD8F1hg==";
//    public static final String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    
    Intent intent;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.toastShortPositive("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.toastShortNegative("支付失败");
                    }
                    intent = new Intent(ConfirmListingActivity.this,MyChecklistActivity.class);
                    intent.putExtra("wa_id",wa_id);
                    intent.putExtra("agent_id",agent_id);
                    startActivity(intent);
                    YEventBuses.post(new YEventBuses.Event("pay"));
                    finish();
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtil.toastShortNegative("\"授权成功\\n\" + String.format(\"authCode:%s\", authResult.getAuthCode())");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtil.toastShortNegative("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    
    @Override
    public int getLayout() {
        return R.layout.activity_confirm_isting;
    }

    @Override
    public String initTitle() {
        return "确认清单";
    }
    
    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        
        
        agent_id = (String)getIntent().getStringExtra("agent_id");
        wa_id = (String)getIntent().getStringExtra("wa_id"); 
        balanceEntity = (BalanceEntity) getIntent().getSerializableExtra("data");
        type = (int)getIntent().getIntExtra("type",0);
        goods_id = (String)getIntent().getStringExtra("goods_id");
        num = (int) getIntent().getIntExtra("num",0);
        item_id = (String)getIntent().getStringExtra("item_id"); 
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingMoreEnabled(false);
        initHeadView();
        
        data.addAll(balanceEntity.getSelected_goods());
        
        beanBaseAdapter = new BaseAdapter<BalanceEntity.SelectedGoodsBean>(this,data) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_confirm_list;
            }
                
            @Override
            protected void getView(BaseViewHolder holder, BalanceEntity.SelectedGoodsBean entity, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.iv_good_img);
                simpleDraweeView.setImageURI(UrlConst.baseUrl()+entity.getOriginal_img());
                
                holder.setText(R.id.tv_name,entity.getGoods_name());
                holder.setText(R.id.tv_model,entity.getSpec_key_name());
                holder.setText(R.id.tv_place,"￥"+entity.getGoods_price());
                holder.setText(R.id.tv_totalNum,"x"+entity.getGoods_num());
                float total = Float.valueOf(entity.getGoods_price())*Float.valueOf(entity.getGoods_num());
                holder.setText(R.id.tv_xiaoji,"共"+entity.getGoods_num()+"件商品 小计：￥"+decimalFormat.format(total));
                
            }
        };

        tv_totalPrice.setText("￥"+balanceEntity.getTotal_price());
        
        beanBaseAdapter.setAnimationsLocked(true);
        recyclerView.setAdapter(beanBaseAdapter);
        
    }

    @Override
    public void initData() {

    }
    
    public void initHeadView(){
        
        viewHead = LayoutInflater.from(ConfirmListingActivity.this).inflate(R.layout.recycler_item_confirm_list_head,
                null);
        TextView tv_shopName= (TextView) viewHead.findViewById(R.id.tv_shopName);
        TextView tv_phone = (TextView)viewHead.findViewById(R.id.tv_phone);
        TextView tv_address = (TextView)viewHead.findViewById(R.id.tv_address);
        
        tv_shopName.setText(balanceEntity.getAgent_info().getName());
        tv_phone.setText(balanceEntity.getAgent_info().getPhone());
        tv_address.setText(balanceEntity.getAgent_info().getAddress());
        recyclerView.addHeaderView(viewHead);
        
    }
    
    @OnClick(R.id.tv_fukuang)
    public void fukuang(){
        
        AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmListingActivity.this);
        builder.setMessage("请确认清单的商品门店库存充足");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                     
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                PatternDialog patternDialog = new PatternDialog(ConfirmListingActivity.this);
                patternDialog.show();
            }
        });
        
        builder.show();
        
        
    }

    @Override
    public void onEventMainThread(final YEventBuses.Event event) {
        super.onEventMainThread(event);
        if(event.is("alipay")||event.is("weixin")){
            if(type==0){
                MyAppointmentRequest.addOrder(ConfirmListingActivity.this,agent_id,wa_id)
                        .compose(DoTransform.<AddOrderEntity>applyScheduler(this,true))
                        .compose(ConfirmListingActivity.this.<AddOrderEntity>bindToLifecycle())
                        .subscribe(new HttpSubscriber<AddOrderEntity>(this) {
                            @Override
                            protected void onSuccess(AddOrderEntity entity) {
                                orderInfo = entity.getPayment_params().getAlipay();
                                weixinBean = entity.getPayment_params().getWeixin();
                                if(event.is("alipay")){
                                    payV2(tv_totalPrice);
                                }else {
                                    weixiPay();
                                }
                                
                            }

                            @Override
                            protected void onFail(String msg) {

                            }
                        });
            }else {
                MyAppointmentRequest.lijijiesuanPay(ConfirmListingActivity.this,goods_id,num+"",
                        wa_id,item_id,agent_id)
                        .compose(DoTransform.<AddOrderEntity>applyScheduler(this,true))
                        .compose(ConfirmListingActivity.this.<AddOrderEntity>bindToLifecycle())
                        .subscribe(new HttpSubscriber<AddOrderEntity>(this) {
                            @Override
                            protected void onSuccess(AddOrderEntity entity) {
                                orderInfo = entity.getPayment_params().getAlipay();
                                weixinBean = entity.getPayment_params().getWeixin();
                                if(event.is("alipay")){
                                    payV2(tv_totalPrice);
                                }else {
                                    weixiPay();
                                }
                            }

                            @Override
                            protected void onFail(String msg) {

                            }
                        });
            }
        }
    }
    
    /**
     * 支付宝支付业务
     *
     * @param v
     */
    public void payV2(View v) {
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        

//        /**
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险； 
//         *
//         * orderInfo的获取必须来自服务端；
//         */
//        boolean rsa2 = true;
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//          
//        
//
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        final String orderInfo = orderParam + "&" + sign;
            
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmListingActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        
        
        
    }
    
    public void weixiPay(){

        boolean isTiaozhuang = true;//是否是 确认清单的跳转
        SPUtil.put(ConfirmListingActivity.this,SPUtil.TIANZHUANG,isTiaozhuang);
        SPUtil.put(ConfirmListingActivity.this,SPUtil.WA_ID,wa_id);
        SPUtil.put(ConfirmListingActivity.this,SPUtil.ARGENT_ID,agent_id);
        SPUtil.put(ConfirmListingActivity.this,SPUtil.PAY_TYPE,1);
        
        IWXAPI msgApi = WXAPIFactory.createWXAPI(ConfirmListingActivity.this,"wx086831d3499ea9c2", true);
        msgApi.registerApp("wx086831d3499ea9c2");

        boolean isWXAppInstalled = msgApi .isWXAppInstalled();
        if(isWXAppInstalled){
            PayReq request = new PayReq();
            request.appId = weixinBean.getAppid();
            request.partnerId = weixinBean.getPartnerid();
            request.prepayId= weixinBean.getPrepayid();
            request.packageValue = "Sign=WXPay";
            request.nonceStr= weixinBean.getNoncestr();
            request.timeStamp= weixinBean.getTimestamp();
            request.sign= weixinBean.getSign();
            msgApi.sendReq(request);
        }else {
            ToastUtil.toastShortPositive("请先安装微信");
        }
        
        
        
    }
    
    

    @Override
    protected void onDestroy() {
        super.onDestroy();
        YEventBuses.unregister(this);
    }
}
